<!DOCTYPE html><html lang="zh-cn"><head><link rel=manifest href=/manifest.json><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="format-detection" content="telephone=no"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><link rel="icon" href="/images/icons/icon.jpg?v=2.0.0-rc.0" type="image/png" sizes="16x16"><link rel="icon" href="/images/icons/icon.jpg?v=2.0.0-rc.0" type="image/png" sizes="32x32"><meta name="description" content="经过jl大佬和hy大佬的指导后重新编写  放GitHublogo章鱼猫的图片来作为引入  what                     Git和GitHub是什么       Git (&#x2F;ɡɪt&#x2F;) is a distributed version-control system for tracking changes in source code during software develo">
<meta name="keywords" content="技术探究">
<meta property="og:type" content="article">
<meta property="og:title" content="Git和GitHub入门">
<meta property="og:url" content="https:&#x2F;&#x2F;mikyming.online&#x2F;2019&#x2F;12&#x2F;03&#x2F;Git%E5%92%8CGitHub%E5%85%A5%E9%97%A8%E6%8C%87%E5%8D%97&#x2F;">
<meta property="og:site_name" content="MikyMing&#39;s Blog">
<meta property="og:description" content="经过jl大佬和hy大佬的指导后重新编写  放GitHublogo章鱼猫的图片来作为引入  what                     Git和GitHub是什么       Git (&#x2F;ɡɪt&#x2F;) is a distributed version-control system for tracking changes in source code during software develo">
<meta property="og:locale" content="zh-cn">
<meta property="og:image" content="https:&#x2F;&#x2F;mikyming.online&#x2F;img&#x2F;git-workflow1.png">
<meta property="og:image" content="https:&#x2F;&#x2F;mikyming.online&#x2F;img&#x2F;distributed.png">
<meta property="og:image" content="https:&#x2F;&#x2F;mikyming.online&#x2F;img&#x2F;svn.jpg">
<meta property="og:image" content="https:&#x2F;&#x2F;mikyming.online&#x2F;img&#x2F;git.jpg">
<meta property="og:updated_time" content="2020-04-21T14:16:37.222Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https:&#x2F;&#x2F;mikyming.online&#x2F;img&#x2F;git-workflow1.png"><meta name="keywords" content="MikyMing, MikyMing's Blog"><meta name="description" content="技术,生活"><title>Git和GitHub入门 | MikyMing's Blog</title><link ref="canonical" href="https://mikyming.online/2019/12/03/Git%E5%92%8CGitHub%E5%85%A5%E9%97%A8%E6%8C%87%E5%8D%97/"><link rel="alternate" href="/atom.xml" type="application/atom+xml"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.12.1/css/all.min.css" type="text/css"><link rel="stylesheet" href="/css/index.css?v=2.0.0-rc.0"><script>var Stun = window.Stun || {};
var CONFIG = {
  root: '/',
  algolia: undefined,
  fontIcon: {"prompt":{"success":"fas fa-check-circle","info":"fas fa-arrow-circle-right","warning":"fas fa-exclamation-circle","error":"fas fa-times-circle"},"copyBtn":"fas fa-copy"},
  sidebar: {"offsetTop":"20px","tocMaxDepth":6},
  header: {"enable":true,"showOnPost":false,"scrollDownIcon":true},
  postWidget: {"endText":true},
  nightMode: {"enable":true},
  back2top: {"enable":true},
  codeblock: {"style":"default","highlight":"ocean","wordWrap":false},
  reward: false,
  fancybox: false,
  zoomImage: {"gapAside":"20px"},
  galleryWaterfall: undefined,
  lazyload: false,
  pjax: undefined,
  externalLink: {"icon":{"enable":true,"name":"fas fa-external-link-alt"}},
  shortcuts: {"switchPost":true},
  prompt: {"copyButton":"Copy","copySuccess":"Copy Success","copyError":"Copy Error"},
  sourcePath: {"js":"js","css":"css","images":"images"},
};

window.CONFIG = CONFIG;</script></head><body><div class="container" id="container"><header class="header" id="header"><div class="header-inner header-inner--height header-inner--bgcolor"><nav class="header-nav header-nav--sticky"><div class="header-nav-inner"><div class="header-nav-menubtn"><i class="fas fa-bars"></i></div><div class="header-nav-menu"><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/"><span class="header-nav-menu-item__icon"><i class="fas fa-home"></i></span><span class="header-nav-menu-item__text">Home</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/archives/"><span class="header-nav-menu-item__icon"><i class="fas fa-folder-open"></i></span><span class="header-nav-menu-item__text">Archives</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/categories/"><span class="header-nav-menu-item__icon"><i class="fas fa-layer-group"></i></span><span class="header-nav-menu-item__text">Categories</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/tags/"><span class="header-nav-menu-item__icon"><i class="fas fa-tags"></i></span><span class="header-nav-menu-item__text">Tags</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="javascript:;" target="_blank" rel="noopener" onclick="return false;"><span class="header-nav-menu-item__icon"><i class="fa fa-address-book"></i></span><span class="header-nav-menu-item__text">友链</span></a><div class="header-nav-submenu"><div class="header-nav-submenu-item"><a class="header-nav-submenu-item__link" href="https://www.bobby285271.top/" target="_blank" rel="noopener"><span class="header-nav-submenu-item__text">BobbyRong</span></a></div><div class="header-nav-submenu-item"><a class="header-nav-submenu-item__link" href="https://blog.ojhdt.com/" target="_blank" rel="noopener"><span class="header-nav-submenu-item__text">ojhdt</span></a></div></div></div></div><div class="header-nav-search"><span class="header-nav-search__icon"><i class="fas fa-search"></i></span><span class="header-nav-search__text">Search</span></div><div class="header-nav-mode"><div class="mode"><div class="mode-track"><span class="mode-track-moon"></span><span class="mode-track-sun"></span></div><div class="mode-thumb"></div></div></div></div></nav></div></header><main class="main" id="main"><div class="main-inner"><div class="content-wrap" id="content-wrap"><div class="content" id="content"><!-- Just used to judge whether it is an article page--><div id="is-post"></div><div class="post"><header class="post-header"><h1 class="post-title">Git和GitHub入门</h1><div class="post-meta"><span class="post-meta-item post-meta-item--createtime"><span class="post-meta-item__icon"><i class="far fa-calendar-plus"></i></span><span class="post-meta-item__info">Created</span><span class="post-meta-item__value">2019-12-03</span></span><span class="post-meta-item post-meta-item--updatetime"><span class="post-meta-item__icon"><i class="far fa-calendar-check"></i></span><span class="post-meta-item__info">Updated</span><span class="post-meta-item__value">2020-04-21</span></span><span class="post-meta-item post-meta-item--wordcount"><span class="post-meta-item__icon"><i class="far fa-file-word"></i></span><span class="post-meta-item__info">Words</span><span class="post-meta-item__value">1.2k</span></span><span class="post-meta-item post-meta-item--visitors"><span class="post-meta-item__icon" data-popover="Visitors" data-popover-pos="up"><i class="fas fa-eye"></i></span><span class="post-meta-item__value" id="busuanzi_value_page_pv"></span></span></div></header><div class="post-body"><p><em>经过jl大佬和hy大佬的指导后重新编写</em></p>
<blockquote>
<p>放GitHublogo章鱼猫的图片来作为引入</p>
</blockquote>
<p><em>what</em></p>

        <h3 id="Git和GitHub是什么"   >
          <a href="#Git和GitHub是什么" class="heading-link"><i class="fas fa-link"></i></a>Git和GitHub是什么</h3>
      <p><strong>Git</strong> (/ɡɪt/) is a distributed version-control system for tracking changes in source code during software development.  –wikipedia<br><strong>GIT</strong>是一个分布式版本控制系统用于跟踪的变化系统的源代码中的软件开发。–维基百科</p>
<p><strong>GitHub</strong> is an American company that provides hosting for software development. Github includes version control using Git, which allows software projects to keep track of all versions and revert to previous versions if necessary.  –wikipedia<br><strong>GitHub</strong>是一家美国公司，为软件开发提供托管。GitHub包含使用Git进行的版本控制，该版本控制允许软件项目跟踪所有版本，并在必要时还原为以前的版本。–维基百科</p>
<p><strong>用人话说Git是啥</strong><br>Git是一种分布式版本控制系统。但它的核心其实是数据库。Git把我们的每一次提交记录到数据库中。我们可以通过对数据库进行查询来了解并回溯每一次提交，这就实现了版本控制。然后我们可以选择将这个数据库完整的克隆到另一台服务器上，这就实现了分布式。</p>
<a id="more"></a>


        <h3 id="Git的工作流程"   >
          <a href="#Git的工作流程" class="heading-link"><i class="fas fa-link"></i></a>Git的工作流程</h3>
      <p>Git将我们的每一次提交放到工作目录的缓存空间，完成保存。然后等你想提交到远程仓库的时候再从缓存区里提交出去。同样的，你也可以从远程仓库将文件下载回工作目录。</p>
<p><img loading="lazy" src="/img/git-workflow1.png" alt="git-workflow1"></p>

        <h3 id="啥是分布式版本控制系统-Distributed-Version-Control"   >
          <a href="#啥是分布式版本控制系统-Distributed-Version-Control" class="heading-link"><i class="fas fa-link"></i></a>啥是分布式版本控制系统(Distributed Version Control)</h3>
      <p>说到分布式版本控制系统就不得不提到集中式版本控制系统，他们最大的差别在于分布式的仓库可以有很多份。其实这是一个去中心化的概念。在集中式版本控制系统中，拥有唯一的中心也就是我们常说的服务器。中央服务器是一切的核心，储存着所有的数据。而分布式版本控制则是一个去中心，或者说是多中心的系统。每一个开发者的本地仓库都拥有着全部的数据。 “push” “pull” 操作则是为了让所有的仓库数据统一而已。</p>
<p><img loading="lazy" src="/img/distributed.png" alt="distributed system"></p>

        <h3 id="Git-VS-SVN"   >
          <a href="#Git-VS-SVN" class="heading-link"><i class="fas fa-link"></i></a>Git VS SVN</h3>
      <div class="table-container"><table>
<thead>
<tr>
<th align="left"></th>
<th align="center">集中式（SVN）</th>
<th align="center">分布式（Git）</th>
</tr>
</thead>
<tbody><tr>
<td align="left">有无中央服务器</td>
<td align="center">有。开发者脱离服务器几乎无法工作</td>
<td align="center">无。开发者有本地仓库</td>
</tr>
<tr>
<td align="left">分支操作</td>
<td align="center">创建分支则所有人都有此分支</td>
<td align="center">分支操作不影响其他人</td>
</tr>
<tr>
<td align="left">提交</td>
<td align="center">直接提交到中央版本库</td>
<td align="center">首先提交到本地缓存区，执行push操作才提交到版本库</td>
</tr>
<tr>
<td align="left">图释</td>
<td align="center"><img loading="lazy" src="/img/svn.jpg" width="50%"/></td>
<td align="center"><img loading="lazy" src="/img/git.jpg" width="50%"/></td>
</tr>
</tbody></table></div>
<p><em>what</em></p>
<blockquote>
<p>// 有一说一git/github的功能详细并没有做,还是沿用了原来的简易版本</p>
</blockquote>

        <h3 id="我们用Git和GitHub来干什么"   >
          <a href="#我们用Git和GitHub来干什么" class="heading-link"><i class="fas fa-link"></i></a>我们用Git和GitHub来干什么</h3>
      <ul>
<li>代码托管    //不解释</li>
<li>项目管理    //如，版本控制、协作编程</li>
<li>资源备份    //如，托管编程环境、备份核心代码</li>
<li>托管静态网页    //如，GitHub Page</li>
<li>个人简历    //你可以在GitHub上展示你自己</li>
<li>查找资料    //GitHub可能是全世界程序方面资料最多的地方</li>
<li>交朋友    //全球最大的同性交友平台</li>
<li>资讯来源    //GitHub热榜！比知乎更有料，比微博更劲爆</li>
</ul>
<p><em>how</em></p>

        <h3 id="Git的安装和使用"   >
          <a href="#Git的安装和使用" class="heading-link"><i class="fas fa-link"></i></a>Git的安装和使用</h3>
      
        <h4 id="安装"   >
          <a href="#安装" class="heading-link"><i class="fas fa-link"></i></a>安装</h4>
      <p><span class="exturl"><a class="exturl__link"   href="https://git-scm.com/book/zh/v2/%E8%B5%B7%E6%AD%A5-%E5%AE%89%E8%A3%85-Git"  target="_blank" rel="noopener">点击此处进入官方安装教程</a><span class="exturl__icon"><i class="fas fa-external-link-alt"></i></span></span></p>

        <h4 id="使用"   >
          <a href="#使用" class="heading-link"><i class="fas fa-link"></i></a>使用</h4>
      <p>让我们先新建一个仓库（文件夹），进入文件夹并打开Git Bash。<br>执行</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ git init</span><br></pre></td></tr></table></div></figure>
<p>接下来你可以执行如下命令以创建一个本地仓库的克隆版本：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ git <span class="built_in">clone</span> /path/to/repository</span><br></pre></td></tr></table></div></figure>
<p>如果是远端服务器上的仓库，你的命令会是这个样子：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ git <span class="built_in">clone</span> username@host:/path/to/repository</span><br></pre></td></tr></table></div></figure>
<p>搭建好仓库后，如果你有所改动可以把它添加到缓存区，使用如下命令：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ git add &lt;filename&gt;</span><br><span class="line">$ git add *		//将所有的改动都添加</span><br></pre></td></tr></table></div></figure>
<p>最后使用如下命令以实际提交改动：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ git commit -m <span class="string">"代码提交信息"</span></span><br></pre></td></tr></table></div></figure>
<p>现在，你的改动已经提交到了 HEAD，但是还没到你的远端仓库。<br>执行如下命令以将这些改动提交到远端仓库：</p>
<figure class="highlight bash"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ git push origin master	//可以把 master 换成你想要推送的任何分支。</span><br></pre></td></tr></table></div></figure>
<p><strong>注意事项</strong></p>
<ul>
<li>git commit 命令一定要添加描述，否则会无法成功运行</li>
</ul>
<p><em>本段参考自<span class="exturl"><a class="exturl__link"   href="https://www.bootcss.com/p/git-guide/"  target="_blank" rel="noopener">https://www.bootcss.com/p/git-guide</a><span class="exturl__icon"><i class="fas fa-external-link-alt"></i></span></span>/</em><br><em>想要深入了解GIt的同学可以前去参考</em></p>
<blockquote>
<p>// Git命令太多，基本命令已经在上文展示故取消Git命令大全板块<br>// 使用git中常见的问题和注意事项过于杂乱，故只提一点</p>
</blockquote>
</div><footer class="post-footer"><div class="post-ending ending"><div class="ending__text">------ END ------</div></div><div class="post-copyright copyright"><div class="copyright-author"><span class="copyright-author__name">Author: </span><span class="copyright-author__value"><a href="https://mikyming.online">MikyMing</a></span></div><div class="copyright-link"><span class="copyright-link__name">Link: </span><span class="copyright-link__value"><a href="https://mikyming.online/2019/12/03/Git%E5%92%8CGitHub%E5%85%A5%E9%97%A8%E6%8C%87%E5%8D%97/">https://mikyming.online/2019/12/03/Git%E5%92%8CGitHub%E5%85%A5%E9%97%A8%E6%8C%87%E5%8D%97/</a></span></div><div class="copyright-notice"><span class="copyright-notice__name">Copyright: </span><span class="copyright-notice__value">All articles in this blog are licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh-cn" rel="external nofollow" target="_blank">BY-NC-SA</a> unless stating additionally</span></div></div><div class="post-tags"><span class="post-tags-item"><span class="post-tags-item__icon"><i class="fas fa-tag"></i></span><a class="post-tags-item__link" href="https://mikyming.online/tags/%E6%8A%80%E6%9C%AF%E6%8E%A2%E7%A9%B6/">技术探究</a></span></div><nav class="post-paginator paginator"><div class="paginator-prev"><a class="paginator-prev__link" href="/2019/12/07/thief/"><span class="paginator-prev__icon"><i class="fas fa-angle-left"></i></span><span class="paginator-prev__text">小偷家族</span></a></div><div class="paginator-next"><a class="paginator-next__link" href="/2019/11/26/docker/"><span class="paginator-prev__text">docker</span><span class="paginator-next__icon"><i class="fas fa-angle-right"></i></span></a></div></nav></footer></div></div></div><div class="sidebar-wrap" id="sidebar-wrap"><aside class="sidebar" id="sidebar"><div class="sidebar-nav"><span class="sidebar-nav-toc current">Catalog</span><span class="sidebar-nav-ov">Overview</span></div><section class="sidebar-toc"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Git和GitHub是什么"><span class="toc-number">1.</span> <span class="toc-text">
          Git和GitHub是什么</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Git的工作流程"><span class="toc-number">2.</span> <span class="toc-text">
          Git的工作流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#啥是分布式版本控制系统-Distributed-Version-Control"><span class="toc-number">3.</span> <span class="toc-text">
          啥是分布式版本控制系统(Distributed Version Control)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Git-VS-SVN"><span class="toc-number">4.</span> <span class="toc-text">
          Git VS SVN</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#我们用Git和GitHub来干什么"><span class="toc-number">5.</span> <span class="toc-text">
          我们用Git和GitHub来干什么</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Git的安装和使用"><span class="toc-number">6.</span> <span class="toc-text">
          Git的安装和使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#安装"><span class="toc-number">6.1.</span> <span class="toc-text">
          安装</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#使用"><span class="toc-number">6.2.</span> <span class="toc-text">
          使用</span></a></li></ol></li></ol></section><!-- ov = overview--><section class="sidebar-ov hide"><div class="sidebar-ov-author"><div class="sidebar-ov-author__avatar"><img class="sidebar-ov-author__avatar_img" src="/images/icons/touxiang.jpg" alt="avatar"></div><p class="sidebar-ov-author__text">write code and love life</p></div><div class="sidebar-ov-social"><a class="sidebar-ov-social-item" href="https://github.com/5522mike/" target="_blank" rel="noopener" data-popover="Github" data-popover-pos="up"><span class="sidebar-ov-social-item__icon"><i class="fab fa-github"></i></span></a><a class="sidebar-ov-social-item" href="mailto:wuyyming@gmail.com" target="_blank" rel="noopener" data-popover="social.email" data-popover-pos="up"><span class="sidebar-ov-social-item__icon"><i class="fas fa-envelope"></i></span></a></div><div class="sidebar-ov-feed"><span class="sidebar-ov-feed-rss"><a class="sidebar-ov-feed-rss__link" href="/atom.xml" target="_blank" rel="noopener"><span class="sidebar-ov-feed-rss__icon"><i class="fas fa-rss"></i></span><span>RSS Subscribe</span></a></span></div><div class="sidebar-ov-state"><a class="sidebar-ov-state-item sidebar-ov-state-item--posts" href="/archives/"><div class="sidebar-ov-state-item__count">24</div><div class="sidebar-ov-state-item__name">Archives</div></a><a class="sidebar-ov-state-item sidebar-ov-state-item--categories" href="/categories/"><div class="sidebar-ov-state-item__count">4</div><div class="sidebar-ov-state-item__name">Categories</div></a><a class="sidebar-ov-state-item sidebar-ov-state-item--tags" href="/tags/"><div class="sidebar-ov-state-item__count">6</div><div class="sidebar-ov-state-item__name">Tags</div></a></div><div class="sidebar-ov-cc"><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh-cn" target="_blank" rel="noopener" data-popover="Creative Commons" data-popover-pos="up"><img src="/images/cc-by-nc-sa.svg"></a></div></section><div class="sidebar-reading"><div class="sidebar-reading-info"><span class="sidebar-reading-info__text">You have read </span><span class="sidebar-reading-info__num">0</span></div><div class="sidebar-reading-line"></div></div></aside></div><div class="clearfix"></div></div></main><footer class="footer" id="footer"><div class="footer-inner"><div><span>Copyright © 2022</span><span class="footer__icon"><i class="fas fa-heart"></i></span><span>MikyMing</span></div><div><span>Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a></span><span> v4.0.0</span><span class="footer__devider">|</span><span>Theme - <a href="https://github.com/liuyib/hexo-theme-stun/" title="Stun" target="_blank" rel="noopener">Stun</a></span><span> v2.0.0-rc.0</span></div><div class="busuanzi"><span class="busuanzi-siteuv"><span class="busuanzi-siteuv__icon" data-popover-pos="up" data-popover="Unique Visitor"><i class="fas fa-user"></i></span><span class="busuanzi-siteuv__value" id="busuanzi_value_site_uv"></span></span><span class="busuanzi-sitepv"><span class="busuanzi-siteuv__icon" data-popover-pos="up" data-popover="Page View"><i class="fas fa-eye"></i></span><span class="busuanzi-siteuv__value" id="busuanzi_value_site_pv"></span></span></div></div></footer><div class="loading-bar" id="loading-bar"><div class="loading-bar__progress"></div></div><div class="back2top" id="back2top"><span class="back2top__icon"><i class="fas fa-rocket"></i></span></div></div><div class="search-mask"></div><div class="search-popup"><span class="search-close"></span><div class="search-input"><input placeholder="Search for Posts (Support multiple keywords)"></div><div class="search-results"></div></div><script src="https://cdn.jsdelivr.net/npm/jquery@v3.4.1/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.ui.min.js"></script><script src="https://cdn.jsdelivr.net/npm/ribbon.js@latest/dist/ribbon.min.js" size="120" alpha="0.6" zIndex="-1"></script><script>function initSearch() {
  var isXML = true;
  var search_path = 'search.json';

  if (!search_path) {
    search_path = 'search.xml';
  } else if (/json$/i.test(search_path)) {
    isXML = false;
  }

  var path = '/' + search_path;
  $.ajax({
    url: path,
    dataType: isXML ? 'xml' : 'json',
    async: true,
    success: function (res) {
      var datas = isXML ? $('entry', res).map(function () {
        // 将 XML 转为 JSON
        return {
          title: $('title', this).text(),
          content: $('content', this).text(),
          url: $('url', this).text()
        };
      }).get() : res;
      var $input = $('.search-input input');
      var $result = $('.search-results');
      // 搜索对象（标题、内容）的权重，影响显示顺序
      var WEIGHT = { title: 100, content: 1 };
      var searchPost = function () {
        var searchText = $input.val().toLowerCase().trim();
        // 根据空白字符分隔关键字
        var keywords = searchText.split(/[\s]+/);
        // 搜索结果
        var matchPosts = [];

        // 有多个关键字时，将原文字整个保存下来
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        // 防止未输入字符时搜索
        if (searchText.length > 0) {
          datas.forEach(function (data) {
            var isMatch  = false;
            // 没有标题的文章使用预设的 i18n 变量代替
            var title = (data.title && data.title.trim()) || '[ Untitled ]';
            var titleLower = title && title.toLowerCase();
            // 删除 HTML 标签 和 所有空白字符
            var content = data.content && data.content.replace(/<[^>]+>/g, '');
            var contentLower = content && content.toLowerCase();
            // 删除重复的 /
            var postURL = data.url && decodeURI(data.url).replace(/\/{2,}/g, '/');
            // 标题中匹配到的关键词
            var titleHitSlice = [];
            // 内容中匹配到的关键词
            var contentHitSlice = [];

            keywords.forEach(function (keyword) {
              /**
              * 获取匹配的关键词的索引
              * @param {String} keyword 要匹配的关键字
              * @param {String} text 原文字
              * @param {Boolean} caseSensitive 是否区分大小写
              * @param {Number} weight 匹配对象的权重。权重大的优先显示
              * @return {Array}
              */
              function getIndexByword (word, text, caseSensitive, weight) {
                if (!word || !text) {
                  return [];
                };

                var startIndex = 0; // 每次匹配的开始索引
                var index = -1;     // 匹配到的索引值
                var result = [];    // 匹配结果

                if (!caseSensitive) {
                  word = word.toLowerCase();
                  text = text.toLowerCase();
                }

                while((index = text.indexOf(word, startIndex)) !== -1) {
                  var hasMatch = false;
                  // 索引位置相同的关键词，保留长度较长的
                  titleHitSlice.forEach(function (hit) {
                    if (hit.index === index && hit.word.length < word.length) {
                      hit.word = word;
                      hasMatch = true;
                    }
                  });
                  startIndex = index + word.length;
                  !hasMatch && result.push({ index: index, word: word, weight: weight });
                }
                return result;
              }
              titleHitSlice = titleHitSlice.concat(getIndexByword(keyword, titleLower, false, WEIGHT.title));
              contentHitSlice = contentHitSlice.concat(getIndexByword(keyword, contentLower, false, WEIGHT.content));
            });

            var hitTitle = titleHitSlice.length;
            var hitContent = contentHitSlice.length;

            if (hitTitle > 0 || hitContent > 0) {
              isMatch = true;
            }
            if (isMatch) {
              ;[titleHitSlice, contentHitSlice].forEach(function (hit) {
                // 按照匹配文字的索引的递增顺序排序
                hit.sort(function (left, right) {
                  return left.index - right.index;
                });
              });
              /**
              * 给文本中匹配到的关键词添加标记，从而进行高亮显示
              * @param {String} text 原文本
              * @param {Array} hitSlice 匹配项的索引信息
              * @param {Number} start 开始索引
              * @param {Number} end 结束索引
              * @return {String}
              */
              function highlightKeyword (text, hitSlice, start, end) {
                if (!text || !hitSlice || !hitSlice.length) {
                  return;
                }

                var result = '';
                var startIndex = start;
                var endIndex = end;
                hitSlice.forEach(function (hit) {
                  if (hit.index < startIndex) {
                    return;
                  }

                  var hitWordEnd = hit.index + hit.word.length;
                  result += text.slice(startIndex, hit.index);
                  result += '<b>' + text.slice(hit.index, hitWordEnd) + '</b>';
                  startIndex = hitWordEnd;
                });
                result += text.slice(startIndex, endIndex);
                return result;
              }

              var postData = {};
              // 文章总的搜索权重
              var postWeight = titleHitSlice.length * WEIGHT.title + contentHitSlice.length * WEIGHT.content;
              // 标记匹配关键词后的标题
              var postTitle = highlightKeyword(title, titleHitSlice, 0, title.length) || title;
              // 标记匹配关键词后的内容
              var postContent;
              // 显示内容的长度
              var SHOW_WORD_LENGTH = 200;
              // 命中关键词前的字符显示长度
              var SHOW_WORD_FRONT_LENGTH = 20;
              var SHOW_WORD_END_LENGTH = SHOW_WORD_LENGTH - SHOW_WORD_FRONT_LENGTH;

              // 截取匹配的第一个字符，前后共 200 个字符来显示
              if (contentHitSlice.length > 0) {
                var firstIndex = contentHitSlice[0].index;
                var start = firstIndex > SHOW_WORD_FRONT_LENGTH ? firstIndex - SHOW_WORD_FRONT_LENGTH : 0;
                var end = firstIndex + SHOW_WORD_END_LENGTH;
                postContent = highlightKeyword(content, contentHitSlice, start, end);
              } else { // 未匹配到内容，直接截取前 200 个字符来显示
                postContent = content.slice(0, SHOW_WORD_LENGTH);
              }
              postData.title = postTitle;
              postData.content = postContent;
              postData.url = postURL;
              postData.weight = postWeight;
              matchPosts.push(postData);
            }
          });
        }

        var resultInnerHtml = '';
        if (matchPosts.length) {
          // 按权重递增的顺序排序，使权重大的优先显示
          matchPosts.sort(function (left, right) {
            return right.weight - left.weight;
          });
          resultInnerHtml += '<ul>';
          matchPosts.forEach(function (post) {
            resultInnerHtml += '<li><a class="search-results-title" href="' + post.url + '">';
            resultInnerHtml += post.title;
            resultInnerHtml += '</a><div class="search-results-content">';
            resultInnerHtml += post.content;
            resultInnerHtml += '</div></li>';
          });
          resultInnerHtml += '</ul>';
        } else {
          resultInnerHtml += '<div class="search-results-none"><i class="far fa-meh"></i></div>';
        }
        $result.html(resultInnerHtml);
      };
      $input.on('input', searchPost);
      $input.on('keyup', function (e) {
        if (e.keyCode === Stun.utils.codeToKeyCode('Enter')) {
          searchPost();
        }
      });
    }
  });
}

function closeSearch () {
  $('body').css({ overflow: 'auto' });
  $('.search-popup').css({ display: 'none' });
  $('.search-mask').css({ display: 'none' });
}

window.addEventListener('DOMContentLoaded', function () {
  Stun.utils.pjaxReloadLocalSearch = function () {
    $('.header-nav-search').on('click', function (e) {
      e.stopPropagation();
      $('body').css('overflow', 'hidden');
      $('.search-popup')
        .velocity('stop')
        .velocity('transition.expandIn', {
          duration: 300,
          complete: function () {
            $('.search-popup input').focus();
          }
        });
      $('.search-mask')
        .velocity('stop')
        .velocity('transition.fadeIn', {
          duration: 300
        });

      initSearch();
    });
    $('.search-mask, .search-close').on('click', function () {
      closeSearch();
    });
    $(document).on('keydown', function (e) {
      // Escape <=> 27
      if (e.keyCode === Stun.utils.codeToKeyCode('Escape')) {
        closeSearch();
      }
    });
  };

  Stun.utils.pjaxReloadLocalSearch();
}, false);</script><script src="https://cdn.jsdelivr.net/gh/sukkaw/busuanzi@latest/bsz.pure.mini.js" async></script><script src="/js/utils.js?v=2.0.0-rc.0"></script><script src="/js/stun-boot.js?v=2.0.0-rc.0"></script><script src="/js/scroll.js?v=2.0.0-rc.0"></script><script src="/js/header.js?v=2.0.0-rc.0"></script><script src="/js/sidebar.js?v=2.0.0-rc.0"></script><script>if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js?t=1648616400595')
    .then(function () {console.log('ServiceWorker Register Successfully.')})
    .catch(function (e) {console.error(e)});
}
</script></body></html>